package com.javaeedev.junit;

import com.javaeedev.junit.Cache;

import net.sourceforge.groboutils.junit.v1.TestRunnable;

public class CacheRunnable extends TestRunnable {

    private Cache cache;
    private boolean read;
    private char ch;

    public CacheRunnable(Cache cache) {
        this.cache = cache;
        this.read = true;
        this.ch = 'x';
    }

    public CacheRunnable(Cache cache, char ch) {
        this.cache = cache;
        this.read = false;
        this.ch = ch;
    }

    @Override
    public void runTest() throws Throwable {
        for(int i=0; i<1000; i++) {
            if(read) {
                char[] cs = cache.read();
                assertTrue("Returned char[] is not the same characters: " + new String(cs), check(cs));
            }
            else {
                cache.write(ch);
            }
        }
    }

    private boolean check(char[] cs) {
        char c = cs[0];
        for(int i=1; i<cs.length; i++) {
            if(c!=cs[i])
                return false;
        }
        return true;
    }
}
